/*
 * Copyright 2010    Sylvere RICHARD
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.infotrafficlux.client.place;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.client.ui.HTMLTable.RowFormatter;
import com.google.gwt.user.client.ui.Widget;
import com.google.infotrafficlux.client.images.MainImagesBundle;
import com.google.infotrafficlux.client.place.PlacePresenter.IPlaceView;
import com.google.infotrafficlux.client.util.GwtMultiMap;
import com.google.infotrafficlux.shared.Formatter;
import com.google.infotrafficlux.shared.GwtPlace;


/**
 * 
 * @author sly
 *
 */
public class PlaceView extends Composite implements IPlaceView {

	private static PlaceViewUiBinder uiBinder = GWT
			.create(PlaceViewUiBinder.class);

	private static final MainImagesBundle imageBundle = GWT
			.create(MainImagesBundle.class);

	interface PlaceViewUiBinder extends UiBinder<Widget, PlaceView> {
	}

	private final Formatter fmt = new Formatter();
	@UiField
	FlexTable table;
	@UiField
	Button next;
	@UiField
	Button previous;

	private Command sortCommand;

	private String[] columnHeaders = new String[] { "ID", "Cita ID",
			"Location", "Highway", "Desc" };

	private int sortDirection = 0;
	private List<GwtPlace> customerData = new ArrayList<GwtPlace>();
	private GwtMultiMap<String, GwtPlace> dataBucket = new GwtMultiMap<String, GwtPlace>();
	private Set<String> sortColumnValues = new TreeSet<String>();

	@Override
	public Command getSortCommand() {
		return sortCommand;
	}

	@Override
	public void setSortCommand(Command sortCommand) {
		this.sortCommand = sortCommand;
	}

	public PlaceView() {

		initWidget(uiBinder.createAndBindUi(this));

		table.setWidth(500 + "px");
		table.setBorderWidth(1);
		table.setCellPadding(4);
		table.setCellSpacing(1);

		resetColumnHeaders();

		RowFormatter rowFormatter = table.getRowFormatter();
		rowFormatter.setStyleName(0, "tableHeader");
		table.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				final Cell cell = table.getCellForEvent(event);
				int row = cell.getRowIndex();
				if (row == 0) {
					sortTable(row, cell.getCellIndex());
				}
			}
		});

	}

	private void resetColumnHeaders() {
		table.setHTML(0, 0, columnHeaders[0] + "&nbsp;<img border='0' src='"
				+ imageBundle.blank().getURL() + "'/>");
		table.setHTML(0, 1, columnHeaders[1] + "&nbsp;<img border='0' src='"
				+ imageBundle.blank().getURL() + "'/>");
		table.setHTML(0, 2, columnHeaders[2] + "&nbsp;<img border='0' src='"
				+ imageBundle.blank().getURL() + "'/>");
		table.setHTML(0, 3, columnHeaders[3] + "&nbsp;<img border='0' src='"
				+ imageBundle.blank().getURL() + "'/>");

		table.setHTML(0, 4, columnHeaders[4] + "&nbsp;<img border='0' src='"
				+ imageBundle.blank().getURL() + "'/>");
	}

	public void sortTable(int row, int col) {
		dataBucket.clear();
		sortColumnValues.clear();
		for (GwtPlace p : customerData) {

			String value = asRow(p)[col];
			dataBucket.put(value, p);
			sortColumnValues.add(value);
		}
		redrawColumnHeaders(col);

		redrawTable();
	}

	private String[] asRow(GwtPlace p) {
		return new String[] { p.getId().toString(), p.getCitaId(),
				p.getLocation().toString(), p.getHighway(), p.getDesc() };
	}

	private void redrawTable() {
		int row = 1;
		List<String> tmp = new ArrayList<String>();
		tmp.addAll(sortColumnValues);
		if (sortDirection == 0) {
			sortDirection = 1;
		} else {
			sortDirection = 0;
			Collections.reverse(tmp);
		}

		for (Iterator<String> iter = tmp.iterator(); iter
				.hasNext();) {
			String key = iter.next();
			List<GwtPlace> l = dataBucket.get(key);
			for (GwtPlace p : l) {
				table.setText(row, 0, Long.toString(p.getId()));
				table.setText(row, 1, p.getCitaId());
				table.setText(row, 2, fmt.format(p.getLocation()));
				table.setText(row, 3, p.getHighway());
				table.setText(row, 4, p.getDesc());
				row++;
			}
		}
	}

	private void redrawColumnHeaders(int column) {
		if (sortDirection == 0) {
			table.setHTML(0, column, columnHeaders[column]
					+ "&nbsp;<img border='0' src='"
					+ imageBundle.arrow_down_16().getURL() + "'/>");
		} else if (sortDirection == 1) {
			table.setHTML(0, column, columnHeaders[column]
					+ "&nbsp;<img border='0' src='"
					+ imageBundle.arrow_up_16().getURL() + "'/>");
		} else {
			table.setHTML(0, column, columnHeaders[column]
					+ "&nbsp;<img border='0' src='"
					+ imageBundle.blank().getURL() + "'/>");
		}
		for (int i = 0; i < columnHeaders.length; i++) {
			if (i != column) {
				table.setHTML(0, i, columnHeaders[i]
						+ "&nbsp;<img border='0' src='"
						+ imageBundle.blank().getURL() + "'/>");
			}
		}
	}

	@Override
	public void setData(List<GwtPlace> result) {
		customerData = result;
		int row = 1;
		resetColumnHeaders();
		for (Iterator<GwtPlace> iter = result.iterator(); iter.hasNext();) {
			GwtPlace p = iter.next();
			table.setText(row, 0, Long.toString(p.getId()));
			table.setText(row, 1, p.getCitaId());
			table.setText(row, 2, fmt.format(p.getLocation()));
			table.setText(row, 3, p.getHighway());
			table.setText(row, 4, p.getDesc());
			row++;
		}
	}

	@Override
	public void clearTable() {

		for (int row = 1; row < table.getRowCount(); row++) {
			for (int col = 0; col < table.getCellCount(row); col++) {
				table.clearCell(row, col);
			}
		}
	}

	public HasClickHandlers getNext() {
		return next;
	}

	public HasClickHandlers getPrevious() {
		return previous;
	}
}
